package com.haha.keymap;

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

import javax.swing.*;
import java.awt.*;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author shenlinnan
 * @date 2025/7/13 18:27
 */
public class GlobalKeyListenerDemo extends JFrame implements NativeKeyListener{

    private JTextArea logArea;
    private JLabel statusLabel;
    private boolean isRecording = false;
    private boolean isF11Pressed = false;

    public GlobalKeyListenerDemo() {
        super("全局键盘监听器示例");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 400);
        setLayout(new BorderLayout());

        // 禁用 JNativeHook 日志
        disableNativeHookLogging();

        // 初始化UI
        initUI();

        // 注册全局键盘钩子
        registerGlobalHook();

        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void disableNativeHookLogging() {
        // 禁用 JNativeHook 的日志输出
        Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
        logger.setLevel(Level.OFF);
        logger.setUseParentHandlers(false);
    }

    private void initUI() {
        // 状态标签
        statusLabel = new JLabel("状态: 未启动记录", SwingConstants.CENTER);
        statusLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        statusLabel.setOpaque(true);
        statusLabel.setBackground(Color.LIGHT_GRAY);
        add(statusLabel, BorderLayout.NORTH);

        // 设置中文语言环境
        Locale.setDefault(Locale.CHINA);

        // 日志区域
        logArea = new JTextArea();
        logArea.setEditable(false);
        logArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        JScrollPane scrollPane = new JScrollPane(logArea);
        add(scrollPane, BorderLayout.CENTER);

        // 控制按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));

        JButton startButton = new JButton("开始记录 (F11)");
        startButton.addActionListener(e -> startRecording());

        JButton stopButton = new JButton("停止记录");
        stopButton.addActionListener(e -> stopRecording());

        JButton clearButton = new JButton("清空日志");
        clearButton.addActionListener(e -> logArea.setText(""));

        buttonPanel.add(startButton);
        buttonPanel.add(stopButton);
        buttonPanel.add(clearButton);

        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void registerGlobalHook() {
        try {
            GlobalScreen.registerNativeHook();
        } catch (NativeHookException ex) {
            logMessage("注册全局钩子失败: " + ex.getMessage());
            JOptionPane.showMessageDialog(this,
                    "无法注册全局键盘钩子: " + ex.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }

        // 添加监听器
        GlobalScreen.addNativeKeyListener(this);
    }

    @Override
    public void nativeKeyPressed(NativeKeyEvent e) {
        int keyCode = e.getKeyCode();

        // 记录 F11 按键
        if (keyCode == NativeKeyEvent.VC_F11) {
            System.out.println("F11");
            isF11Pressed = true;

            if (isRecording) {
                logMessage("F11 按下 - 记录位置");
                // 在这里添加记录位置的逻辑
                Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
                logMessage("鼠标位置: (" + mouseLocation.x + ", " + mouseLocation.y + ")");
            }
        }

        // 记录其他按键
        if (isRecording) {
            String keyText = NativeKeyEvent.getKeyText(keyCode);
            logMessage("按键按下: " + keyText + " (代码: " + keyCode + ")");
        }
    }

    @Override
    public void nativeKeyReleased(NativeKeyEvent e) {
        int keyCode = e.getKeyCode();

        // 处理 F11 释放
        if (keyCode == NativeKeyEvent.VC_F11) {
            isF11Pressed = false;
        }
    }

    @Override
    public void nativeKeyTyped(NativeKeyEvent e) {
        // 这里可以处理按键字符输入
        if (isRecording) {
            logMessage("按键输入: '" + e.getKeyChar() + "'");
        }
    }

    private void startRecording() {
        isRecording = true;
        statusLabel.setText("状态: 记录中... (按 F11 记录位置)");
        statusLabel.setBackground(new Color(144, 238, 144)); // 浅绿色
        logMessage("开始记录键盘事件...");
    }

    private void stopRecording() {
        isRecording = false;
        statusLabel.setText("状态: 未启动记录");
        statusLabel.setBackground(Color.LIGHT_GRAY);
        logMessage("停止记录键盘事件");
    }

    private void logMessage(String message) {
        SwingUtilities.invokeLater(() -> {
            logArea.append(message + "\n");
            logArea.setCaretPosition(logArea.getDocument().getLength());
        });
    }

    @Override
    public void dispose() {
        try {
            GlobalScreen.unregisterNativeHook();
        } catch (NativeHookException e) {
            e.printStackTrace();
        }
        super.dispose();
    }

    public static void main(String[] args) {
        // 在main方法开始处
        System.setProperty("file.encoding", "UTF-8");

        SwingUtilities.invokeLater(() -> new GlobalKeyListenerDemo());
    }

}
